package net.xgclass.online_xgclass.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.xgclass.online_xgclass.model.entity.VideoOrder;
import net.xgclass.online_xgclass.model.request.VideoOrderAndUser;
import net.xgclass.online_xgclass.model.request.VideoOrderRequest;
import net.xgclass.online_xgclass.service.VideoOrderService;
import net.xgclass.online_xgclass.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/v1/pri/order")
public class VideoOrderController {


    @Autowired
    private VideoOrderService videoOrderService;


    /**
     * 下单接口
     * @return
     */
    @RequestMapping("save")
    public JsonData saveOrder(@RequestBody(required=false) VideoOrderRequest videoOrderRequest, HttpServletRequest request){

        Integer userId = (Integer) request.getAttribute("user_id");


        int rows = videoOrderService.save(userId, videoOrderRequest.getVideoId());

        return rows == 0 ? JsonData.buildError("下单失败"):JsonData.buildSuccess();
    }


    /**
     * 订单列表
     * @param request
     * @return
     */
    @GetMapping("list")
    public JsonData listOrder(HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("user_id");

        List<VideoOrder> videoOrderList = videoOrderService.listOrderByUserId(userId);

        return JsonData.buildSuccess(videoOrderList);

    }

    //********************************后台******************************************//

    /**
     * 查询订单  后台
     * @return
     */
    @RequestMapping(
            value = {"listOrder"},
            method = {RequestMethod.GET}
    )
    public PageInfo<VideoOrderAndUser> listOrder(int pagenum, int pagesize ,String byname){
        PageHelper.startPage(pagenum,pagesize);
        List<VideoOrderAndUser> listOrder = videoOrderService.listOrder(byname);
        PageInfo<VideoOrderAndUser> pageInfo =new PageInfo<>(listOrder);
        return pageInfo;

    }

    /**
     * 根据id删除订单
     * @param id
     * @return
     */
    @RequestMapping(
            value = {"/{id}"},
            method = {RequestMethod.DELETE}
    )
    public JsonData delOrderById(@PathVariable Integer id){
        int flag = videoOrderService.delOrderById(id);
        return flag==1 ? JsonData.buildSuccess():JsonData.buildError("删除订单失败");
    }

}
